/**
 * 文件操作模块
 * 开发者：dev_C
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "../Include/file_pub.h"
#include "../Include/student_pub.h"
#include "../Include/course_pub.h"

// 外部声明
extern Student students[MAX_STUDENT];
extern int student_count;
extern Course courses[MAX_COURSES];
extern int course_count;

void init_file_system() {
    printf("文件系统初始化完成\n");
}

int load_data_from_files() {
    FILE* file;
    char line[256];
    int loaded_count = 0;

    // 加载学生数据
    printf("正在加载学生数据...\n");
    file = fopen("student.txt", "r");
    if(file != NULL) {
        while(fgets(line, sizeof(line), file)) {
            // 跳过空行和注释行
            if(strlen(line) <= 1 || line[0] == '#') continue;

            // 移除换行符
            line[strcspn(line, "\n")] = 0;

            // 解析学生数据格式：学号,姓名,课程1,课程2,...,总学分
            char* token = strtok(line, ",");
            if(token == NULL) continue;

            char id[20], name[50];
            strcpy(id, token);          // 学号

            token = strtok(NULL, ",");
            if(token == NULL) continue;
            strcpy(name, token);        // 姓名

            // 添加学生
            if(add_student(id, name) == 0) {
                Student* student = find_student_by_id(id);
                if(student) {
                    // 解析已选课程和学分
                    int is_credit_field = 0;
                    token = strtok(NULL, ",");
                    
                    while(token != NULL && student->course_count < MAX_COURSES_PER_STUDENT) {
                        // 检查是否是学分字段（数字）- 通常是最后一个字段
                        if(token[0] >= '0' && token[0] <= '9' && !is_credit_field) {
                            student->total_credits = atoi(token);
                            is_credit_field = 1;
                        } else {
                            // 这是课程编号
                            strcpy(student->selected_courses[student->course_count], token);
                            student->course_count++;
                        }
                        token = strtok(NULL, ",");
                    }
                }
                loaded_count++;
            }
        }
        fclose(file);
        printf("成功加载 %d 名学生数据\n", loaded_count);
    } else {
        printf("学生数据文件不存在，将创建新文件\n");
    }

    // 加载课程数据
    loaded_count = 0;
    printf("正在加载课程数据...\n");
    file = fopen("class.txt", "r");
    if(file != NULL) {
        while(fgets(line, sizeof(line), file)) {
            // 跳过空行和注释行
            if(strlen(line) <= 1 || line[0] == '#') continue;

            // 移除换行符
            line[strcspn(line, "\n")] = 0;

            // 解析课程数据格式：课程编号,名称,性质,学时,学分,已选人数,人数上限
            char* token = strtok(line, ",");
            if(token == NULL) continue;

            char id[20], name[50], type[20];
            int hours, credits, selected, max;

            strcpy(id, token);

            token = strtok(NULL, ",");
            if(token == NULL) continue;
            strcpy(name, token);

            token = strtok(NULL, ",");
            if(token == NULL) continue;
            strcpy(type, token);

            token = strtok(NULL, ",");
            if(token == NULL) continue;
            hours = atoi(token);

            token = strtok(NULL, ",");
            if(token == NULL) continue;
            credits = atoi(token);

            token = strtok(NULL, ",");
            if(token == NULL) continue;
            selected = atoi(token);

            token = strtok(NULL, ",");
            if(token == NULL) continue;
            max = atoi(token);

            // 添加课程
            if(add_course(id, name, type, hours, credits, max) == 0) {
                Course* course = find_course_by_id(id);
                if(course) {
                    course->selected_count = selected;
                }
                loaded_count++;
            }
        }
        fclose(file);
        printf("成功加载 %d 门课程数据\n", loaded_count);
    } else {
        printf("课程数据文件不存在，将创建新文件\n");
    }

    return 0;
}

void input_data_from_keyboard() {
    // 命令行输入模式提示已移除
}

int save_data_to_files() {
    FILE* file;
    int saved_count = 0;

    // 保存学生数据
    printf("正在保存学生数据...\n");
    file = fopen("student.txt", "w");
    if(file != NULL) {
        fprintf(file, "# 学生数据文件\n");
        fprintf(file, "# 格式：学号,姓名,已选课程(逗号分隔),总学分\n");

        for(int i = 0; i < student_count; i++) {
            fprintf(file, "%s,%s", students[i].id, students[i].name);

            // 写入已选课程
            for(int j = 0; j < students[i].course_count; j++) {
                fprintf(file, ",%s", students[i].selected_courses[j]);
            }

            // 写入总学分
            fprintf(file, ",%d\n", students[i].total_credits);
            saved_count++;
        }
        fclose(file);
        printf("成功保存 %d 名学生数据\n", saved_count);
    } else {
        printf("错误：无法打开学生数据文件进行写入\n");
        return -1;
    }

    // 保存课程数据
    saved_count = 0;
    printf("正在保存课程数据...\n");
    file = fopen("class.txt", "w");
    if(file != NULL) {
        fprintf(file, "# 课程数据文件\n");
        fprintf(file, "# 格式：课程编号,名称,性质,学时,学分,已选人数,人数上限\n");

        for(int i = 0; i < course_count; i++) {
            fprintf(file, "%s,%s,%s,%d,%d,%d,%d\n",
                    courses[i].id, courses[i].name, courses[i].type,
                    courses[i].hours, courses[i].credits,
                    courses[i].selected_count, courses[i].max_students);
            saved_count++;
        }
        fclose(file);
        printf("成功保存 %d 门课程数据\n", saved_count);
    } else {
        printf("错误：无法打开课程文件进行写入\n");
        return -1;
    }

    return 0;
}

void log_operation(OperationType op_type, const char* target_id, const char* details){
    FILE* log_file = fopen("log.log", "a");
    if(log_file != NULL) {
        // 获取当前时间
        time_t now = time(NULL);
        struct tm* timeinfo = localtime(&now);
        char timestamp[20];
        strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", timeinfo);

        // 操作类型名称映射
        const char* op_names[] = {
            "ADD_STUDENT", "DELETE_STUDENT", "MODIFY_STUDENT",
            "ADD_COURSE", "DELETE_COURSE", "MODIFY_COURSE",
            "SELECT_COURSE", "DROP_COURSE"
        };

        // 写入日志
        fprintf(log_file, "[%s] %s %s %s\n",
                timestamp, op_names[op_type], target_id, details);
        fclose(log_file);

        // 同时在控制台显示
        printf("记录日志：%s %s %s\n", op_names[op_type], target_id, details);
    } else {
        printf("错误：无法打开日志文件\n");
    }
}
